import { myActivityPage,deleteActivity } from '@/api/OperationManage/marketingManagements'
import { weekDateList,activeState,activityType,activityMemberType,businessScopeType } from "@/views/OperateManagement/dict"
import { useConfirm } from "@/hooks/index"

const searchTableRef = ref(null)

export const useMyActivityData =()=>{
  return {
    searchTableRef,
  }
}

export const useCurd =()=>{
  const router = useRouter()
  // 表格数据
  const tableData = ref([])
  const tableLoading = ref(false)
  const total = ref(0)

  // 搜索
  const handlerSearch = async (data) => {
    try{
      tableLoading.value = true
      const res = await myActivityPage(data)
      tableData.value = res.records
      total.value = res.total
    }finally{
      tableLoading.value = false
    }
  }

  // 表格配置
  const btnLefts = []
  const btnRights = []
  const actionActivity = async (opsType,row) => {
    const text = opsType ? '终止' : '删除'
    ElMessageBox.confirm(`是否${text}【${row.activityName}】活动?`,'提示',{
      type:'warning',
      confirmButtonText:text,
      confirmButtonClass:'el-button--danger',
      beforeClose:async (action,instance,done)=>{
        const func = async ()=>{
          const params = {
            activityId:row.id,
            opsType,
          }
          return await deleteActivity(params)
        }
        const res = await useConfirm(action,instance,done,func)
        if(res){
          ElMessage.success(text+'成功')
          searchTableRef.value.handlerSearch()
        }
      }
    })
  }
  const tableForms = ref([
    {
      type: "input",
      prop: 'activityName',
      placeholder: "活动名称",
      label: "",
      model: '',
    },
    {
      type: "select",
      prop: 'activityType',
      placeholder: "活动类型",
      filterable:true,
      data:activityType,
      label: "",
      model: '',
    },
    {
      type: "select",
      prop: 'activityStatus',
      placeholder: "活动状态",
      filterable:true,
      data:activeState,
      label: "",
      model: '',
    },
    {
      type: "datePicker",
      prop: ["createStartTime", "createEndTime"],
      startPlaceholder: "创建开始时间",
      endPlaceholder: "创建结束时间",
      label: "",
      model: [],
    },
  ])
  const tableConfig = ref([
    {
      label:'活动名称',
      prop:'activityName',
      minWidth:162,
      type:'slot',
      slotName:'activityName',
      textOverflow:true,
    },
    {
      label:'活动类型',
      prop:'activityType',
      minWidth:88,
      format:(value)=>{
        return activityType.find(item=>item.value===value)?.label || '-'
      },
    },
    {
      label:'活动对象',
      prop:'activityMemberType',
      minWidth:158,
      textOverflow:true,
      format:(value,row)=>{
        if(row.activityMember == 0){
          return `全部会员(${value == 0 ? '全部' : '未消费会员'})`
        }else{
          return `指定会员等级(${row.activityMemberValue.join(',')})`
        }
      },
    },
    {
      label:'活动门店及业务',
      prop:'businessScope',
      minWidth:130,
      format:(value,row)=>{
        if(value){
          return row.activityStoreData.map(item=>item.storeName).filter(Boolean).join('，')
        }
        return businessScopeType.find(item=>item.value===value)?.label || '-'
      },
      textOverflow:true,
    },
    {
      label:'状态',
      prop:'activityStatus',
      minWidth:74,
      format:(value)=>{
        return activeState.find(item=>item.value===value)?.label || '-'
      },
    },
    {
      label:'活动时间',
      textOverflow:true,
      prop:'activityTimeType',
      minWidth:116,
      format:(value,row)=>{
        if(value){
          return `${row.activityStartTime}-${row.activityEndTime}`
        }
        return row.typeValue.map(item=>weekDateList[item-1]).filter(Boolean).join('，')
      },
    },
    {
      label:'创建时间',
      prop:'createTime',
      minWidth:114
    },
    {
      type:'action',
      label:'操作',
      fixed: "right",
      minWidth:296,
      btns:[
        {
          label:()=>'数据',
          type:'primary',
          show:()=>true,
          click:(row)=>{
            router.push({
              name:'ActivityData',
              query:{
                id:row.id
              }
            })
          }
        },
        {
          label:()=>'编辑',
          type:'success',
          show:(row)=>row.activityStatus === 1,
          click:(row)=>{
            if(row.activityType === 3){
              router.push({name:'NewcomerDiscountEdit',query:{id:row.id}})
            }else if(row.activityType === 2){
              router.push({name:'DiscountRestrictionEdit',query:{id:row.id}})
            }
          }
        },
        {
          label:()=>'复制',
          type:'primary',
          show:(row)=>row.activityType !== 3,
          click:(row)=>{
            if(row.activityType === 3){
              router.push({name:'NewcomerDiscountCopy',query:{id:row.id,copy:1}})
            }else if(row.activityType === 2){
              router.push({name:'DiscountRestrictionCopy',query:{id:row.id,copy:1}})
            }
          }
        },
        {
          label:()=>'终止',
          type:'danger',
          show:(row)=>{
            return row.activityStatus === 2 ? false : true
          },
          click:(row)=>{
            actionActivity(true,row)
          }
        },
        {
          label:()=>'删除',
          type:'danger',
          show:(row)=>{
            return row.activityType !== 3 ? row.activityStatus == 2 ? true : false :false
          },
          click:(row)=>{
            actionActivity(false,row)
          }
        }
      ]
    }
  ])
  return {
    tableLoading,
    total,
    tableData,
    btnLefts,
    btnRights,
    tableConfig,
    tableForms,
    handlerSearch,
  }
}